<template>
  <u-popup :show="showPopup" :round="10" :safeAreaInsetBottom="false" :closeOnClickOverlay="true" @close="closePopup"
    @open="openPopup">
    <scroll-view scroll-y="true" class="recharge-popup">
        
      <view class="pay-tip-txt">感谢您支持作者，解锁后可继续观看</view>

      <view class="video-name">
        <view class="txt" v-if="videoInfo">{{ `${ videoInfo.video_name } · 第${ videoInfo.sort }集` }}</view>

        <button slot="value" open-type="im" :data-im-id="imId" class="im-btn" @im="ImBtnCallback" @error="ImBtnError">
          <u-icon name="kefu-ermai" color="#666666" :style="{
            marginRight: '4px',
            fontSize: '18px'
          }"></u-icon>
          <text :style="{
            fontSize: '15px',
            color: '#666666'
          }">联系客服</text>
        </button>
      </view>

      <!-- 剩余钻石 -->
      <view class="balance-wrapper">
        <view class="balance">
          <text>余额: {{ balance }}钻石 <text v-if="give_balance !== 0">（含赠送{{ give_balance }}钻石）</text></text>
        </view>

        <view class="gold-pay-info" v-if="one_price && one_price !== 0">
          <text>解锁本集：{{ one_price }}金币</text>
        </view>
      </view>

      <view class="pay-template-warpper">
        <view class="template-item" 
          v-for="(item, index) of payTemplateList" :key="item.id"
          @click="selectItem(item)"
        >
          <view :class="(item.pay_type === 1 && item.pay_day == 365) ? 'template-tag hj' : 'template-tag'" v-if="item.corner_text">{{ item.corner_text }}</view>
          <image class="template-bg" v-if="item.corner_text"
            :src="OSSImgUrl(`${ 
            (item.pay_type === 1 && item.pay_day == 365) ? 'pay-template-bg-hj.png' : 'pay-template-bg.png' 
            }`)"
          ></image>
          <image mode="aspectFit" class="template-bg-type" v-if="item.corner_text"
            :src="OSSImgUrl(`${ 
              (item.pay_type === 1 && item.pay_day == 365) ? 
              'pay-template-bg-type-hj.png' : 
              'pay-template-bg-type'+ item.pay_type +'.png'}`)"
          ></image>
          <view class="template-content"
            :style="{
              borderRadius: ( item.is_default === 1) ? '7px' : 'unset',
              backgroundColor:  ( item.is_default === 1) ? '#fff' : 'unset'
            }"
          >
            <view class="pay-money">{{ item.text_pay }}</view>
            <view class="pay-gold">
              <image style="height: 48rpx;" mode="widthFix" :src="OSSImgUrl(`${ (item.pay_type === 1 && item.pay_day == 365) ? 'vip-icon.png' : 'gold-icon.png' }`)" />
              <view class="gold-content">{{ item.text_get }}</view>
            </view>
            <view class="pay-give"
              :style="{
                color: item.is_default === 1 ? '#FD6F09' : '#fff',
              }"
            >{{ item.text_gift }}</view>
          </view>
        </view>
      </view>

      <!-- 充值说明 -->
      <view class="agreement">
        <view>充值说明：</view>
        <block v-for="item of describeList">
          <view v-if="(typeof item === 'string')">{{ item }}</view>
          <block v-else>
            <block v-for="child of item">
              <text v-if="child.includes('《')" class="link" @click="goToOtherPage('pay')">{{ child }}</text>
              <block v-else>
                {{ child }}
              </block>
            </block>
          </block>
        </block>
      </view>
    </scroll-view>
    <u-toast ref="uToast"></u-toast>
  </u-popup>
</template>

<script>
import { getApiPayTemplate, getApiPayParams, getOrderStatus } from '@/api/payTemplate'
import { getPayDescribe } from "@/api/teleplay"
import { updateUserInfo, OSSImgUrl } from '@/utils'
import { showMessage } from '../../utils/message'
// 处理乘法精度丢失
import Decimal from "decimal.js"
export default {
  props: {
    showPopup: {
      type: Boolean,
      required: true,
    },
    page: {
      type: String,
      required: true,
    },
    videoID: {
      type: Number,
      default: 0,
    },
    videoInfo: {
      type: Object,
      default: null
    },
    currentVideoSort: {
      type: Number,
      default: 0
    },
    IsUseAdPay: {
      type: Number,
      default: 0
    },
  },
  data() {
    return {
      id: 57,
      payTemplateList: [], //充值模版列表
      balance: 0, //钻石余额
      combi_id: 0, //充值模版组合id
      template_id: 0, //充值模版id
      give_balance: 0,
      timer: null,//定时器
      count: 0,//记录请求次数 
      flag: true,//节流阀

      imId: this.$store.state.global.ImId,
      describeList: [],
      one_price: 0
    }
  },
  async created() {
    

  },
  methods: {
    OSSImgUrl: OSSImgUrl,
    formatText(text) {

      // 正则表达式匹配《xxx》
      const regex = /《(.*?)》/g;
      let match;
      let lastIndex = 0;
      const resultArray = [];

      // 使用 exec 方法找到所有匹配项
      while ((match = regex.exec(text)) !== null) {
        // 添加匹配项之前的文本（如果有的话）
        const beforeMatch = text.slice(lastIndex, match.index).trim();
        if (beforeMatch !== "") {
          resultArray.push(beforeMatch);
        }

        // 添加匹配项本身（即《xxx》）
        resultArray.push(match[0]);

        // 更新 lastIndex 以指向下一个要处理的文本部分的起始位置
        lastIndex = regex.lastIndex;
      }

      // 添加最后一个匹配项之后的文本（如果有的话），包括标点符号
      const afterLastMatch = text.slice(lastIndex).trim();
      if (afterLastMatch !== "") {
        resultArray.push(afterLastMatch);
      }

      // 输出结果数组
      return resultArray
    },

    ImBtnCallback(e) {
      console.log("跳转IM客服成功", e.detail);
    },
    ImBtnError(e) {
      console.log("拉起IM客服失败", e.detail);
    },
    // 0.打开弹层
    async openPopup() {
      let userInfo = uni.getStorageSync('userInfo')

      console.log("videoinfo", this.videoInfo)
      const res1 = await getPayDescribe({
        eid: userInfo.eid
      })
      const pattern = /《.*?》/;

      if (res1.code === 200) {
        this.describeList = res1.data.map((item) => {
          if(pattern.test(item)){
            return this.formatText(item)
          }
          return item
        })
      }

      this.getPayTemplate()
    },
    // 1.获取充值列表
    async getPayTemplate() {
      let userInfo = uni.getStorageSync('userInfo')
      // 如果获取到的是Json字符串就转换数据
      typeof userInfo === 'object' ? userInfo : userInfo = JSON.parse(userInfo)
      const eid = userInfo.eid
      if (!eid) return
      const { data } = await getApiPayTemplate(eid, this.videoID, this.currentVideoSort)
      this.combi_id = data.combi_id
      this.template_id = data.template_id
      this.one_price = data.one_price
      this.payTemplateList = data.list

      // const list = []
      // for (const key in data) {
      //   if (!['combi_id', 'template_id'].includes(key)) {
      //     list.push(data[key])
      //   }
      //   // 储存combi_id和template_id
      //   if (key === 'combi_id') {
      //     this.combi_id = data[key]
      //   }
      //   if (key === 'template_id') {
      //     this.template_id = data[key]
      //   }
      // }
      console.log("🚀 ~ getPayTemplate ~ payTemplateList:", this.payTemplateList)
      // 获取用户余额 
      const { balance, give_balance } = uni.getStorageSync('balance')
      // 如果没有获取到余额就为0
      const balanceNum = balance ? balance : 0
      const giveNum = give_balance ? give_balance : 0
      this.balance = balanceNum + giveNum
      this.give_balance = giveNum
    },
    // 2.选择充值=》使用lodash节流
    async selectItem({ pay_type, id, pay_money }) {
      if (this.flag) {
        // // 2.1修改选中
        this.payTemplateList.forEach(item => {
          // 如果id相同则为当前选中项
          if (item.id === id) {
            item.is_default = 1
          } else {
            item.is_default = 0
          }
        })
        this.flag = false
        const eid = uni.getStorageSync('userInfo').eid
        const aid = this.$store.state.user.defaultParams.aid
        const channel_id = this.$store.state.user.defaultParams.channel_id

        // 2.2获取支付的必要参数 =>充值钻石/vip接口 
        const res = await getApiPayParams({
          eid,
          order_type: pay_type,
          pay_money,
          channel_id,
          aid,
          oid_package: id,
          oid_template: this.template_id,
          oid_combi: this.combi_id,
          product_id: this.videoID,
          sort: this.videoInfo?.sort || 0
        })



        console.log("data-data", res);
        if (res.data.type === 1) { // 钻石
          uni.showLoading({
            title: '支付请求中...',
            mask: true,
          })

          const thmeData = res.data

          tt.requestOrder({
            data: res.data.data,
            byteAuthorization: res.data.byteAuthorization,
            success: (res) => {
              console.log("🚀 ~ 下单成功:", res)

              tt.getOrderPayment({
                orderId: res.orderId,
                success: (res) => {
                  uni.hideLoading()
                  console.log("🚀 ~ 收银台拉起成功:", res)

                  this.timer = setInterval(async () => {
                    // 2.3.3定时执行任务
                    this.handleTimeOut(this.timer, eid, thmeData.order_id, async () => {
                      // loading关闭后执行 
                      // 支付成功更新用户信息
                      await updateUserInfo()
                      // 向父组件派发事件
                      this.$emit('paySuccess')
                      // 关闭弹窗
                      this.closePopup()
                      showMessage('充值成功')
                    })
                  }, 1000)
                },
                fail: (err) => {
                  console.log("🚀 ~ 收银台拉起失败:", err)
                  if(err.errNo == 9){
                    this.timer = setInterval(async () => {
                      // 2.3.3定时执行任务
                      this.handleTimeOut(this.timer, eid, thmeData.order_id, async () => {
                        // loading关闭后执行 
                        // 支付成功更新用户信息
                        await updateUserInfo()
                        // 向父组件派发事件
                        this.$emit('paySuccess')
                        // 关闭弹窗
                        this.closePopup()
                        showMessage('充值成功')
                      })
                    }, 1000)
                  }
                  uni.hideLoading()
                }
              })

              // 
            },
            fail: (res) => {
              console.log("🚀 ~ 下单失败:", res)
              uni.hideLoading()
            },
            complete: () => {
              console.log("结束");
            }
          })

        } else { // jsAPi
          const data = res.data;

          uni.showLoading({
            title: '支付请求中...',
            mask: true,
          })

          // 2.3 调起抖音支付
          uni.requestPayment({
            provider: 'toutiao',
            service: 5,
            orderInfo: {
              order_id: data.dy_order_id,
              order_token: data.dy_order_token
            },
            success: async (res) => {//只要调起充值都会回调成功,真正的支付成功需要判断code  
              // code为0支付成功
              if (res.code === 0) {
                // 2.3.1开启loading
                uni.showLoading({
                  title: '加载中',
                  mask: true,
                })
                // 2.3.2开启定时器
                this.timer = setInterval(async () => {
                  // 2.3.3定时执行任务
                  this.handleTimeOut(this.timer, eid, data.order_id, async () => {
                    // loading关闭后执行 
                    // 支付成功更新用户信息
                    await updateUserInfo()
                    // 向父组件派发事件
                    this.$emit('paySuccess')
                    // 关闭弹窗
                    this.closePopup()
                    showMessage('充值成功')
                  })
                }, 1000)
              }
              // 关闭Loading加载提示
              uni.hideLoading()
              // }
            },
            fail: (e) => {
              uni.hideLoading()
            },
          })
        }



        setTimeout(() => {
          this.flag = true
        }, 1000)
      }
    },
    goToOtherPage(url) {
      uni.navigateTo({ url: `/pages_sub2/agreement/${url}` })
    },
    // 3. 关闭弹层
    closePopup() {
      this.$emit('update:showPopup', false)
    },
    // 4.格式化支付金额
    formatPayMoney(number) {
      const money = new Decimal(number).mul(new Decimal(100))
      return money
    },
    async handleTimeOut(timer, eid, order_id, fn) {
      this.count++
      const { code } = await getOrderStatus(eid, order_id)
      // 当接口返回200或者10秒后清除定时器
      console.log("支付后订单查询确认次数", this.count, code)
      if (code === 200 || this.count === 10) {
        fn()
        clearInterval(timer)//清除定时器
        uni.hideLoading()//关闭loading 
        this.count = 0
      }
    }
  },
}
</script>
<style lang="scss" scoped>

.pay-tip-txt{
  font-size: 34rpx;
  font-weight: 700;
}

.pay-template-warpper{
  margin-top: 70rpx;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;

  .template-item {
    position: relative;
    width: 48%;
    height: 190rpx;
    box-sizing: border-box;
    padding: 5px;
    background-color: #F8F8F8;
    border-radius: 7px;

    &:nth-child(n + 3){
      margin-top: 70rpx;
    }

    
    
    .template-tag{
      position: absolute;
      top: 0;
      left: 0;
      transform: translate(0px, -45%);
      z-index: 30;

      box-sizing: border-box;
      padding: 12rpx 20rpx;
      font-size: 28rpx;
      color: #fff;
      border-radius: 14px 0 14px 0;
      background: linear-gradient(to bottom, #FFC9A0 10%, #FF6A00 90%);

      &.hj {
        background: #000;
      }
    }

    .template-bg{
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
    }

    .template-bg-type {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
    }

    .template-content {
      position: relative;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;

      .pay-money {
        font-size: 32rpx;
        font-weight: 600;
      }

      .pay-gold {
        margin-top: 10rpx;
        display: flex;
        align-items: center;

        .gold-content{
          font-size: 28rpx;
          color: #393939;
          margin-right: 10rpx;
        }

        image {
          width: 44rpx;
        }
      }

      .pay-give {
        margin-top: 10rpx;
        font-size: 22rpx;
        color: #fff;
      }
    }
  }

}

.video-name{
  margin-top: 30rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .txt {
    font-size: 32rpx;
    color: #7E7D76;
  }
  
  .im-btn {
    flex: 0 0 auto !important;
    display: inline-flex !important;
    align-items: center !important;
    width: auto !important;
    min-width: 0 !important;
    padding: 0 !important;
    background: none !important;
    line-height: normal !important;
    margin: 0;

    &::after {
      border: none !important;
    }
  }
}

.recharge-popup {
  position: relative;
  background: linear-gradient(to bottom, #FFE6D3 10%, #FFF 40%);
  height: 78vh;
  padding: 20px 15px 10px;
  box-sizing: border-box;


  .info-text {
    padding: 0rpx 0 20rpx;
    color: #666;
  }

  height: 78vh;
  padding: 36rpx 30rpx 0rpx;
  box-sizing: border-box;


  .balance-wrapper {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 30rpx;

    .balance {
      font-size: 32rpx;
      color: #FD6F09;
    }

    .gold-pay-info {
      font-size: 32rpx;
      color: #FD6F09;
    }
  }

  .gold-pay-info {
    // width: 242rpx;
    height: 40rpx;
    // margin-top: 18rpx;
    font-size: 28rpx;
    color: #999999;
    display: flex;
  }

  .agreement {
    z-index: 99;
    margin-top: 12rpx;
    font-size: 26rpx;
    color: #8f8f8f;

    view:nth-child(1) {
      color: black;
      font-weight: 700;
      margin-bottom: 14rpx;
    }

    .link {
      color: blue;
    }
  }
}


</style>
